<template>
  <div class="forecast-center">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <div class="header-content">
        <h1>
          <el-icon><TrendCharts /></el-icon>
          智能预测中心
        </h1>
        <p class="subtitle">基于AI算法的业务数据预测与分析</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateForecast">
          <el-icon><Plus /></el-icon>
          新建预测任务
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6" v-for="stat in statsData" :key="stat.label">
        <el-card shadow="hover" class="stat-card" :class="stat.type">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="40"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
              <div class="stat-trend" :class="stat.trend > 0 ? 'up' : 'down'">
                <el-icon><component :is="stat.trend > 0 ? 'Top' : 'Bottom'" /></el-icon>
                {{ Math.abs(stat.trend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预测功能卡片 -->
    <div class="forecast-modules">
      <h2 class="section-title">
        <el-icon><Grid /></el-icon>
        预测模块
      </h2>
      <el-row :gutter="20">
        <el-col :span="8" v-for="module in forecastModules" :key="module.id">
          <el-card shadow="hover" class="module-card" @click="handleModuleClick(module)">
            <div class="module-content">
              <div class="module-icon" :style="{ background: module.color }">
                <el-icon :size="50"><component :is="module.icon" /></el-icon>
              </div>
              <div class="module-info">
                <h3>{{ module.title }}</h3>
                <p>{{ module.description }}</p>
                <div class="module-stats">
                  <span><el-icon><Clock /></el-icon> {{ module.lastUpdate }}</span>
                  <span><el-icon><Check /></el-icon> 准确率: {{ module.accuracy }}%</span>
                </div>
              </div>
              <div class="module-badge" v-if="module.badge">
                <el-tag :type="module.badgeType">{{ module.badge }}</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预测任务列表 -->
    <div class="forecast-tasks">
      <h2 class="section-title">
        <el-icon><List /></el-icon>
        最近预测任务
        <el-button link @click="viewAllTasks">查看全部</el-button>
      </h2>
      <el-table :data="taskList" stripe style="width: 100%">
        <el-table-column prop="taskName" label="任务名称" min-width="200">
          <template #default="{ row }">
            <div class="task-name">
              <el-icon><Document /></el-icon>
              {{ row.taskName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="预测类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTaskTypeColor(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="period" label="预测周期" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accuracy" label="准确率" width="100">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.accuracy" 
              :color="getAccuracyColor(row.accuracy)"
              :show-text="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button link type="success" @click="handleAnalyze(row)">
              <el-icon><DataAnalysis /></el-icon>分析
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 预测模型配置 -->
    <div class="model-config">
      <h2 class="section-title">
        <el-icon><Setting /></el-icon>
        AI模型配置
      </h2>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span><el-icon><MagicStick /></el-icon> 时间序列预测模型</span>
                <el-tag type="success">运行中</el-tag>
              </div>
            </template>
            <div class="model-info">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="模型类型">ARIMA + LSTM</el-descriptions-item>
                <el-descriptions-item label="版本号">v2.3.1</el-descriptions-item>
                <el-descriptions-item label="训练数据量">50万条</el-descriptions-item>
                <el-descriptions-item label="准确率">94.5%</el-descriptions-item>
                <el-descriptions-item label="最后更新">2024-01-15</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag type="success">已优化</el-tag>
                </el-descriptions-item>
              </el-descriptions>
              <div class="model-actions">
                <el-button type="primary" size="small">重新训练</el-button>
                <el-button size="small">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span><el-icon><MagicStick /></el-icon> 机器学习预测模型</span>
                <el-tag type="success">运行中</el-tag>
              </div>
            </template>
            <div class="model-info">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="模型类型">Random Forest + XGBoost</el-descriptions-item>
                <el-descriptions-item label="版本号">v3.1.0</el-descriptions-item>
                <el-descriptions-item label="训练数据量">80万条</el-descriptions-item>
                <el-descriptions-item label="准确率">92.8%</el-descriptions-item>
                <el-descriptions-item label="最后更新">2024-01-18</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag type="success">已优化</el-tag>
                </el-descriptions-item>
              </el-descriptions>
              <div class="model-actions">
                <el-button type="primary" size="small">重新训练</el-button>
                <el-button size="small">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新建预测任务对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建预测任务" width="600px">
      <el-form :model="newTask" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="newTask.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="预测类型">
          <el-select v-model="newTask.type" placeholder="请选择预测类型">
            <el-option label="销售预测" value="sales" />
            <el-option label="库存预测" value="inventory" />
            <el-option label="成本预测" value="cost" />
            <el-option label="需求预测" value="demand" />
            <el-option label="财务预测" value="finance" />
            <el-option label="客户流失预测" value="churn" />
          </el-select>
        </el-form-item>
        <el-form-item label="预测周期">
          <el-select v-model="newTask.period" placeholder="请选择预测周期">
            <el-option label="未来7天" value="7days" />
            <el-option label="未来15天" value="15days" />
            <el-option label="未来30天" value="30days" />
            <el-option label="未来季度" value="quarter" />
            <el-option label="未来半年" value="halfyear" />
            <el-option label="未来一年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="预测模型">
          <el-select v-model="newTask.model" placeholder="请选择预测模型">
            <el-option label="时间序列模型(ARIMA)" value="arima" />
            <el-option label="LSTM神经网络" value="lstm" />
            <el-option label="随机森林" value="rf" />
            <el-option label="XGBoost" value="xgboost" />
            <el-option label="集成模型" value="ensemble" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据范围">
          <el-date-picker
            v-model="newTask.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="newTask.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTask">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 统计数据
const statsData = ref([
  {
    label: '总预测任务',
    value: '2,456',
    icon: 'Document',
    type: 'primary',
    trend: 12.5
  },
  {
    label: '运行中任务',
    value: '38',
    icon: 'Loading',
    type: 'success',
    trend: 8.3
  },
  {
    label: '平均准确率',
    value: '93.2%',
    icon: 'CircleCheck',
    type: 'warning',
    trend: 2.1
  },
  {
    label: '节省成本',
    value: '¥328万',
    icon: 'Money',
    type: 'danger',
    trend: 15.8
  }
])

// 预测模块
const forecastModules = ref([
  {
    id: 'sales',
    title: '销售预测',
    description: '基于历史销售数据，预测未来销售趋势',
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    lastUpdate: '2小时前',
    accuracy: 94.5,
    badge: 'HOT',
    badgeType: 'danger',
    path: '/forecast/sales'
  },
  {
    id: 'inventory',
    title: '库存预测',
    description: '预测未来库存需求，优化库存管理',
    icon: 'Box',
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    lastUpdate: '1小时前',
    accuracy: 92.3,
    badge: 'NEW',
    badgeType: 'success',
    path: '/forecast/inventory'
  },
  {
    id: 'cost',
    title: '成本预测',
    description: '预测未来成本变化趋势，辅助预算制定',
    icon: 'Money',
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    lastUpdate: '3小时前',
    accuracy: 91.8,
    badge: 'AI',
    badgeType: 'warning',
    path: '/forecast/cost'
  },
  {
    id: 'demand',
    title: '需求预测',
    description: '分析市场需求变化，提前做好备货',
    icon: 'DataAnalysis',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    lastUpdate: '30分钟前',
    accuracy: 93.7,
    badge: '',
    badgeType: '',
    path: '/forecast/demand'
  },
  {
    id: 'finance',
    title: '财务预测',
    description: '预测现金流、利润等财务指标',
    icon: 'Wallet',
    color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    lastUpdate: '4小时前',
    accuracy: 89.5,
    badge: '',
    badgeType: '',
    path: '/forecast/finance'
  },
  {
    id: 'churn',
    title: '客户流失预测',
    description: '预测客户流失风险，提前预警干预',
    icon: 'Warning',
    color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    lastUpdate: '5小时前',
    accuracy: 88.2,
    badge: 'NEW',
    badgeType: 'success',
    path: '/forecast/churn'
  }
])

// 任务列表
const taskList = ref([
  {
    id: 1,
    taskName: '2024年Q1销售预测',
    type: '销售预测',
    period: '未来90天',
    status: '已完成',
    accuracy: 94,
    createTime: '2024-01-10 14:30:25'
  },
  {
    id: 2,
    taskName: '春节库存需求预测',
    type: '库存预测',
    period: '未来30天',
    status: '运行中',
    accuracy: 88,
    createTime: '2024-01-15 09:15:10'
  },
  {
    id: 3,
    taskName: '原材料成本趋势预测',
    type: '成本预测',
    period: '未来180天',
    status: '已完成',
    accuracy: 92,
    createTime: '2024-01-08 16:45:33'
  },
  {
    id: 4,
    taskName: '新品需求预测分析',
    type: '需求预测',
    period: '未来60天',
    status: '运行中',
    accuracy: 85,
    createTime: '2024-01-12 11:20:15'
  },
  {
    id: 5,
    taskName: '现金流预测报告',
    type: '财务预测',
    period: '未来季度',
    status: '已完成',
    accuracy: 90,
    createTime: '2024-01-05 08:30:45'
  }
])

// 新建任务对话框
const createDialogVisible = ref(false)
const newTask = reactive({
  name: '',
  type: '',
  period: '',
  model: '',
  dateRange: [],
  remark: ''
})

// 处理模块点击
const handleModuleClick = (module) => {
  router.push(module.path)
}

// 刷新数据
const handleRefresh = () => {
  ElMessage.success('数据已刷新')
}

// 创建预测任务
const handleCreateForecast = () => {
  createDialogVisible.value = true
}

// 提交任务
const handleSubmitTask = () => {
  if (!newTask.name || !newTask.type) {
    ElMessage.warning('请填写必要信息')
    return
  }
  ElMessage.success('预测任务创建成功')
  createDialogVisible.value = false
  // 重置表单
  Object.keys(newTask).forEach(key => {
    if (Array.isArray(newTask[key])) {
      newTask[key] = []
    } else {
      newTask[key] = ''
    }
  })
}

// 查看全部任务
const viewAllTasks = () => {
  router.push('/forecast/tasks')
}

// 查看任务详情
const handleView = (row) => {
  router.push(`/forecast/task-detail/${row.id}`)
}

// 分析任务
const handleAnalyze = (row) => {
  ElMessage.info(`正在分析任务：${row.taskName}`)
}

// 删除任务
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这个预测任务吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 获取任务类型颜色
const getTaskTypeColor = (type) => {
  const colorMap = {
    '销售预测': 'primary',
    '库存预测': 'success',
    '成本预测': 'warning',
    '需求预测': 'info',
    '财务预测': 'danger',
    '客户流失预测': ''
  }
  return colorMap[type] || ''
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    '已完成': 'success',
    '运行中': 'primary',
    '待处理': 'info',
    '失败': 'danger'
  }
  return typeMap[status] || ''
}

// 获取准确率颜色
const getAccuracyColor = (accuracy) => {
  if (accuracy >= 90) return '#67c23a'
  if (accuracy >= 80) return '#e6a23c'
  return '#f56c6c'
}
</script>

<style scoped lang="scss">
.forecast-center {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30px;
  border-radius: 12px;
  color: white;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-content {
    h1 {
      font-size: 28px;
      margin: 0 0 8px 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .subtitle {
      margin: 0;
      opacity: 0.9;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .stat-card {
    border-radius: 12px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .stat-content {
      display: flex;
      gap: 15px;

      .stat-icon {
        width: 70px;
        height: 70px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-bottom: 8px;
        }

        .stat-trend {
          font-size: 12px;
          display: inline-flex;
          align-items: center;
          gap: 3px;
          padding: 2px 8px;
          border-radius: 4px;

          &.up {
            color: #67c23a;
            background: #f0f9ff;
          }

          &.down {
            color: #f56c6c;
            background: #fef0f0;
          }
        }
      }
    }
  }
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;

  .el-button {
    margin-left: auto;
  }
}

.forecast-modules {
  margin-bottom: 20px;

  .module-card {
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s;
    margin-bottom: 20px;
    position: relative;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    }

    .module-content {
      display: flex;
      gap: 15px;
      position: relative;

      .module-icon {
        width: 80px;
        height: 80px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        flex-shrink: 0;
      }

      .module-info {
        flex: 1;

        h3 {
          font-size: 18px;
          margin: 0 0 8px 0;
          color: #303133;
        }

        p {
          font-size: 14px;
          color: #606266;
          margin: 0 0 12px 0;
        }

        .module-stats {
          display: flex;
          gap: 15px;
          font-size: 12px;
          color: #909399;

          span {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }

      .module-badge {
        position: absolute;
        top: -10px;
        right: -10px;
      }
    }
  }
}

.forecast-tasks {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 12px;

  .task-name {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.model-config {
  background: white;
  padding: 20px;
  border-radius: 12px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .model-info {
    .model-actions {
      margin-top: 15px;
      display: flex;
      gap: 10px;
    }
  }
}
</style>

